package com.esiag.isidis.fi.pdsTeam.jms.connection;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

public abstract class AbstractConnectionFactory {
  private Session session;
  private Connection connection;
  private ConnectionFactory factory;

  @SuppressWarnings("rawtypes")
  public AbstractConnectionFactory(Class msgClass) throws JMSException {
    factory = new ActiveMQConnectionFactory(getURL(msgClass));
  }

  public void start() throws JMSException {
    connection = factory.createConnection();
    connection.start();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
  }

  public void close() throws JMSException {
    connection.close();
  }

  public MessageProducer getProducer(String QUEUE) throws JMSException {
    Destination destination = session.createQueue(QUEUE);
    return session.createProducer(destination);
  }

  public MessageConsumer getConsumer(String QUEUE) throws JMSException {
    Destination destination = session.createQueue(QUEUE);
    return session.createConsumer(destination);
  }

  public MessageProducer createTopicProducer(String pTopic) throws JMSException {
    Destination destination = session.createTopic(pTopic);
    return session.createProducer(destination);
  }

  public MessageConsumer createTopicConsumer(String pTopic) throws JMSException {
    Destination destination = session.createTopic(pTopic);
    return session.createConsumer(destination);
  }

  public Session getSession() {
    return session;
  }

  @SuppressWarnings("rawtypes")
  abstract String getURL(Class msgClass);
}